import { Context, h, Schema } from 'koishi'
// import { readFileSync } from 'fs';
// import path from 'node:path';
// import { readFile } from 'fs/promises';

import {} from 'koishi-plugin-adapter-onebot';


export const name = 'onebot-music-card'

// export interface Config {}
// export const Config: Schema<Config> = Schema.object({})

export const Config = Schema.intersect([

  Schema.object({

    presetList: Schema.array(
      Schema.object({
        id: Schema.string(),
        url: Schema.string().role('link'),
        title: Schema.string().role('textarea', { rows: [2, 4] }),
        audio: Schema.string().role('link'),
        image: Schema.string().role('link'),
      })
    ).role('table').default(
      [
        {
          id: 'mcresource', 
          url: 'http://mc.vincentzyu233.cn:55555/',
          title: '资源包光影手动下载',
          audio: '',
          image: 'https://q1.qlogo.cn/g?b=qq&nk=1830540513&s=640'
        },
        {
          id: 'mcclient', 
          url: 'http://mc.vincentzyu233.cn:50405/',
          title: 'mc国际版客户端光影手动下载',
          audio: '',
          image: 'https://q1.qlogo.cn/g?b=qq&nk=1830540513&s=640'
        },
        // https://mc.vincentzyu233.cn/qsfrontend/#/
        {
          id: 'mcscoreboard', 
          url: 'https://mc.vincentzyu233.cn/qsfrontend/#/',
          title: '神秘qwq小服服跑酷计分板',
          audio: '',
          image: 'https://q1.qlogo.cn/g?b=qq&nk=3056516992&s=640'
        },
        {
          id: 'yuanshen', 
          url: 'http://m.gamecenter.qq.com/directout/detail/1110976923?_wv=2164260896&_wwv=44&ADTAG=ark.gameshare&autodownload=1&pf=invite&appid=1110976923&notShowPub=1&asyncMode=3&appType=1&_nav_bgclr=ffffff&_nav_titleclr=ffffff&_nav_txtclr=ffffff&_nav_anim=true&_nav_alpha=0&adtag=aio.qianduan.1104466820.5',
          title: '原神启动',
          audio: '',
          image: 'https://img2.baidu.com/it/u=887603848,3165320269&fm=253&fmt=auto&app=138&f=JPEG?w=121&h=121'
        },
        {
          id: 'fake_yuanshen', 
          url: 'http://m.gamecenter.qq.com/directout/detail/1110976923?_wv=2164260896&_wwv=44&ADTAG=ark.gameshare&autodownload=1&pf=invite&appid=1110976923&notShowPub=1&asyncMode=3&appType=1&_nav_bgclr=ffffff&_nav_titleclr=ffffff&_nav_txtclr=ffffff&_nav_anim=true&_nav_alpha=0&adtag=aio.qianduan.1104466820.5',
          title: '想和你建立情侣关系',
          audio: '',
          image: 'http://mms1.baidu.com/it/u=3290387404,674608078&fm=253&app=138&f=PNG?w=243&h=243'
        },
        {
          id: 'fake_xingtie', 
          url: 'https://static.gamecenter.qq.com/xgame/dist/activity/page/static/launch_qq.html?url=https%3A%2F%2Fspeed.gamecenter.qq.com%2Fpushgame%2Fv1%2Fdetail%3Fappid%3D1112198072%26ADTAG%3Dark.gameshare%26_wv%3D2164260864%26_wwv%3D448%26from_old_gamecenter%3D1%26autodownload%3D1%26autolaunch%3D1%26origin%3Dm.gamecenter.qq.com%26j_from%3D301https',
          title: '想和你建立情侣关系',
          audio: '',
          image: 'http://mms1.baidu.com/it/u=3290387404,674608078&fm=253&app=138&f=PNG?w=243&h=243'
        },
      ]
    ),

    maxUrlLen: Schema.number().default(60).min(10)

  }).description("预设")

])

export function apply(ctx: Context, config) {

  // const ys_img_path = path.join(__dirname, '../assets/genshin.jpg');
  // const ys_img_base64_string = readFileSync(ys_img_path).toString('base64');
  // const ys_img_base64_withhead = `data:image/jpeg;base64,${ys_img_base64_string}`;
  // const YS_LOGO_URL = "https://upload.wikimedia.org/wikipedia/zh/9/94/Genshin_Impact.jpg"
  const YS_LOGO_URL = "https://img2.baidu.com/it/u=887603848,3165320269&fm=253&fmt=auto&app=138&f=JPEG?w=121&h=121"

  ctx.command("amj", "\t发送自定义音乐卡片")
    .alias("awa_music_json")
    .alias("自定义音乐卡片")
    .option("arg0_url", '-u, --url <arg0_url:string> 链接')
    .option("arg1_audio", '-a, --audio <arg1_audio:string> 音频')
    .option("arg2_title", '-t, --title <arg2_title:string> 标题')
    .option("arg3_list", '-l, -list <arg3_list:boolean> 预设列表')
    .option("arg4_index", '-i, --index <arg4_index:number> 想要选择的那个预设的索引')
    .action( async ( {session, options} ) => {
      const MAX_URL_LEN = config.maxUrlLen;
      // await session.send(`options.arg4_index = ${options.arg4_index}`); //如果没传就是undefined

      if ( options.arg3_list ){
        let presetListMsg = `[awa_music_json]预设列表:\n`;
        const n = config.presetList.length;
        for ( let i=0; i<n; i++ ){
          const o = config.presetList[i];
          presetListMsg += `
            <message>
              <author name="No.${i+1} / ${n}"/>
                ↓ No: ${i+1} / ${n} ↓
            </message>
            <message>
              <author name="No.${i+1} / ${n}"/>
              \no.id = \t\t${o.id}
              \no.url = \t\t${o.url.slice(0,MAX_URL_LEN)}${o.url.length > MAX_URL_LEN ? '...' : '' }
              \no.title = \t\t${o.title}
              \no.audio = \t${o.audio.slice(0,MAX_URL_LEN)}${o.audio.length > MAX_URL_LEN ? '...' : '' }
              \no.image = \t${o.image.slice(0,MAX_URL_LEN)}${o.image.length > MAX_URL_LEN ? '...' : '' }
              ${h.image(o.image)}
            </message>
            `;
        }
        presetListMsg = `<message forward>\n` + presetListMsg + `</message>\n`;
        await session.send(presetListMsg);
        return;
      }

      // const tryMsgId = await session.send(h.quote(session.messageId) + "尝试发送音乐卡片...");

      let amj_url: string;
      let amj_audio: string;
      let amj_title: string;
      let amj_image: string;

      if( options.arg4_index !== undefined ){
        if ( options.arg4_index < 0 ){
          await session.send(h.quote(session.messageId) + `index < 0, which is invalid.`);
        }
        if ( options.arg4_index >= config.presetList.length ){
          await session.send(h.quote(session.messageId) + `index >= config.presetList.length, which is invalid.`);
        } 
        const o = config.presetList[options.arg4_index];
        amj_url = o.url;
        amj_audio = o.audio;
        amj_title = o.title;
        amj_image = o.image;
      } else {
        amj_url = options.arg0_url ? options.arg0_url : "https://ys.mihoyo.com/";
        amj_audio = options.arg1_audio ? options.arg1_audio : "https://api.qijieya.cn/meting/?type=url&id=2720752954";
        amj_title = options.arg2_title ? options.arg2_title : "原神??启动!!!";
        amj_image = YS_LOGO_URL;
      }

      if ( session.quote ){
        const firstImgUrl = await extractFirstImageUrl(session.quote.content);
        if ( firstImgUrl !== ""){
          // await session.send(`[debug]有回复消息并且回复消息的第一张图片的url firstImgUrl = ${firstImgUrl}`);
          // amj_image = `https://192.168.31.84:8707/fastapi_once/?link=${encodeURIComponent(firstImgUrl)}`;
          // amj_image = `http://mc.vincentzyu233.cn:58707/fastapi_once/?link=${encodeURIComponent(firstImgUrl)}`;
          amj_image = firstImgUrl;
        }
      }
    
      let argsMsg = `[awa_music_json]尝试发送音乐卡片...args:\n`;
      argsMsg += `amj_url = \t\t${amj_url.slice(0,MAX_URL_LEN)}${amj_url>MAX_URL_LEN ? '...' : ''}\n`
      argsMsg += `amj_audio = \t\t${amj_audio.slice(0,MAX_URL_LEN)}${amj_audio>MAX_URL_LEN ? '...' : ''}\n`
      argsMsg += `amj_title = \t\t${amj_title}\n`
      argsMsg += `amj_image = \t\t${amj_image.slice(0,MAX_URL_LEN)}${amj_image>MAX_URL_LEN ? '...' : ''}\n`
      const argsMsgId = await session.send( h.quote(session.messageId) + argsMsg );

      await session.onebot._request(
        'send_group_msg',
        {
          "group_id": session.guildId,
          "message": 
            {
              "type": "music",
              "data": {
                  "type": "custom",
                  "url": `${amj_url}`,
                  "audio": `${amj_audio}`,
                  "title": `${amj_title}`,
                  "image": `${amj_image}`
              }
            }
        }
      )

      // await session.bot.deleteMessage(session.channelId, String(tryMsgId) );
      // await session.bot.deleteMessage(session.channelId, String(argsMsgId) );


    } )

    const extractFirstImageUrl = async (content) => {
      ctx.logger.info('[debug]现在在extractFirstImageUrl');
      if (!content) {
          // throw Error('content是空的');
          ctx.logger.info('[debug]content是空的，在extractFirstImageUrl中()');
          return "";
      }

      try {
          ctx.logger.info("extractFirstImageUrl content:", content);

          let elementContent = content;
          if (typeof content === 'string') {
              elementContent = h.parse(`${content}`); // 确保 content 被解析为 Element
          }

          let url = '';

          const imgElements = h.select(elementContent, 'img, image, mface');
          if (imgElements.length > 0) {
              const firstElement = imgElements[0];
              url = firstElement.attrs?.src || firstElement.attrs?.url || ''; // 优先取 src，然后取 url
          }

          ctx.logger.info("[debug]extractFirstImageUrl解析结果： url = ", url);
          return url;
      } catch (error) {
          ctx.logger.error("extractFirstImageUrl error:", error);
          // throw Error("有错误:" + error);
          return ''; // 发生错误时返回空字符串，避免程序崩溃
      }


  };

}
